package com.app.service.Impl;

import com.app.mapper.AdminUserMapper;
import com.app.mapper.SysLogMapper;
import com.app.model.AdminUserModel;
import com.app.model.SysLog;
import com.app.service.ISysLogService;
import com.app.vo.LogVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 日志表 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2023-12-01
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements ISysLogService {
    @Autowired
    private SysLogMapper sysLogMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public LogVo selectLogList(Integer page, Integer limit, String title, Integer adminId) {
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();

        if (title != null && !title.equals("")) {
            queryWrapper.like("title", title);
        }
        if (adminId != null && adminId != 0) {
            queryWrapper.eq("user_id", adminId);
        }
        Integer count = sysLogMapper.selectCount(queryWrapper);
        queryWrapper.select("id", "title", "type","remote_addr", "ip_sources", "user_id", "create_time");
        queryWrapper.orderByDesc("create_time");
        Page<SysLog> logPage = new Page<>();
        logPage.setCurrent(page);
        logPage.setSize(limit);
        Page<SysLog> logPage1 = sysLogMapper.selectPage(logPage, queryWrapper);
        for (int i = 0; i < logPage1.getRecords().size(); i++) {
            if (logPage1.getRecords().get(i).getType() != null && logPage1.getRecords().get(i).getType().equals("1")) {
                logPage1.getRecords().get(i).setTypeText("系统日志");
            } else if (logPage1.getRecords().get(i).getType() != null) {
                logPage1.getRecords().get(i).setTypeText("操作日志");
            }
            AdminUserModel adminUserModel = adminUserMapper.selectById(logPage1.getRecords().get(i).getUserId());
            if (adminUserModel != null) {
                logPage1.getRecords().get(i).setUserName(adminUserModel.getRealName());
            }
        }
        LogVo vo = new LogVo();
        vo.setList(logPage1.getRecords());
        vo.setCount(count);
        return vo;
    }

    @Override
    public void deleteLogList(Integer id) {
        sysLogMapper.deleteById(id);
    }

    @Override
    public SysLog selectLogById(Integer id) {
        return sysLogMapper.selectById(id);
    }

    @Override
    public void insert(SysLog sysLog) {
        sysLogMapper.insert(sysLog);
    }
}
